var Router = require('koa-router');
var router = new Router();
const service = require('../service')

router.get('/hello', (ctx, next) => {
	ctx.session.userinfo = ctx.request.body;
	ctx.body = {msg: 'hello you'}
});
router.post('/login', (ctx, next) => {
	ctx.session.userinfo = ctx.request.body;
	console.log("req body ---->", ctx.request.body);
	ctx.body = {msg: 'login success'}
});

router.post('/login-test', (ctx, next) => {
	console.log("login test @@", {userinfo: ctx.session.userinfo});
	ctx.body = {msg:'yes',userinfo: ctx.session.userinfo}
});

let test = new Router()

test.post('/role', async(ctx, next) => {
	try{
		let data = ctx.request.body
		await service.test.addRole(data)
		ctx.body = {msg: 'success'}
	}catch(err){
		ctx.body = {code: 1, msg: `fail ${err}`}
	}
});
test.post('/article', async(ctx, next) => {
	try{
		let data = ctx.request.body
		await service.test.addArticle(data)
		ctx.body = {msg: 'success'}
	}catch(err){
		ctx.body = {code: 1, msg: `fail ${err}`}
	}
});
test.get('/article/:id', async(ctx, next) => {
	try{
		let {id } = ctx.request.params
		let data
		if(id==='list'){
			data= await service.test.getArticleList(id)
		}else{
			data= await service.test.getArticleOne(id)
		}
		ctx.body = {msg: 'success', data}
	}catch(err){
		ctx.body = {code: 1, msg: `fail ${err}`}
	}
});
test.post('/cat', async(ctx, next) => {
	try{
		let data = ctx.request.body
		await service.test.addCat(data)
		ctx.body = {msg: 'success'}
	}catch(err){
		ctx.body = {code: 1, msg: `fail ${err}`}
	}
});
test.get('/cat/:id', async(ctx, next) => {
	try{
		let {id} = ctx.request.params
		let data
		if(id==='list'){
			data = await service.test.getCatList(id)
		}else{
			data = await service.test.getCatOne(id)
		}
		ctx.body = {msg: 'success', data: data || {}}
	}catch(err){
		ctx.body = {code: 1, msg: `fail ${err}`}
	}
});
test.post('/user', async(ctx, next) => {
	try{
		let data = ctx.request.body
		await service.test.addUser(data)
		ctx.body = {msg: 'success'}
	}catch(err){
		ctx.body = {code: 1, msg: `fail ${err}`}
	}
});

router.use('/test', test.routes(), test.allowedMethods())

module.exports = router
